new Vue({
    el: '#app',
    data() {
        return {
            form: [],
            formData: [{}],
            indexData: [],
            nodeKey: '',
            loading: false,
            sortable: null,
        }
    },
    mounted() {
        let ls_URL = window.location.href;
        this.nodeKey = getQueryObject(ls_URL, "nodeKey");// 获取 nodeKey 参数
        this.getData();
        this.$nextTick(() => { //拖拽排序
            var $ul = document.querySelector('#colum tbody')
            $ul.addEventListener('selectstart', function (e) {
                e.preventDefault();
            })
            this.sortable = Sortable.create($ul, {
                handle: '#move',
                draggable: '.el-table__row',
                animation: 150,
                onUpdate: (event) => {
                    let newIndex = event.newIndex, oldIndex = event.oldIndex;
                    $li = $ul.children[newIndex], $oldLi = $ul.children[oldIndex]
                    //先删除移动的节点, 再插入移动的节点到原有节点，还原了移动的操作
                    $ul.removeChild($li)
                    if (newIndex > oldIndex) {
                        $ul.insertBefore($li, $oldLi)
                    } else {
                        $ul.insertBefore($li, $oldLi.nextSibling)
                    }
                    //通过改变vue遍历数组移动节点
                    let item = this.formData[oldIndex];
                    this.formData.splice(oldIndex, 1);
                    this.formData.splice(newIndex, 0, item);
                    this.formData.forEach((item, index) => {
                        item.index = index;
                    })
                }
            })
        })
    },
    computed: {
        ALTER_TABLE() {
            let SQL = "";
            //字段属性
            this.formData.forEach(obj => {
                let is = false;
                const keys = Object.keys(obj);
                for (const key of keys) {
                    if (key.endsWith('_Original')) continue;
                    const originalKey = `${key}_Original`;
                    if (!obj.hasOwnProperty(originalKey)) {
                        break;
                    }
                    if (obj[key] !== obj[originalKey]) {
                        is = true;
                        break;
                    }
                }
                if (is) {
                    SQL += "MODIFY COLUMN `" + obj.COLUMN_NAME + "` " + obj.COLUMN_TYPE + (obj.COLUMN_TYPE != 'varchar' ? ' ' : "(" + obj.COLUMN_LENGTH + ") ") + "CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci " + (obj.COLUMN_DEFAULT != 'NULL' ? "DEFAULT '" + obj.COLUMN_DEFAULT + "' " : '') + (obj.IS_NULLABLE ? '' : 'NOT ') + "NULL " + (obj.COLUMN_COMMENT != '' ? "COMMENT '" + obj.COLUMN_COMMENT + "'" : '') + ",\r\n"
                }

            })
            //表备注
            if (this.form.TABLE_COMMENT != this.form.TABLE_COMMENT_Original) {
                SQL += "COMMENT = '" + this.form.TABLE_COMMENT + "',\r\n";
            }
            //添加头
            if (SQL) {
                SQL = "ALTER TABLE `" + this.form.TABLE_NAME + "`\r\n" + SQL.replace(/,([^,]*)$/, ';$1');
            }
            return { SQL }
        }
    },
    methods: {
        getData() {
            httpRequest({
                hostApi: BASE_URL1,
                url: '/generalQueryAllTableName',
                type: 'GET'
            }).then(res => {
                if (res.Status == 'success') {
                    this.form = configOriginal(res.Data.filter(i => i.TABLE_NAME == this.nodeKey)[0]);
                } else {
                    this.$message({
                        message: '系统错误，请联系开发者!',
                        type: 'error'
                    })
                }
            }).catch(xhr => {
                this.$message({
                    message: '系统错误，请联系开发者!',
                    type: 'error'
                })
            })

            httpRequest({
                hostApi: BASE_URL1,
                url: `/generalQueryAllColumnByTableName?TableName=${this.nodeKey}`,
                type: 'GET'
            }).then(res => {
                if (res.Status == 'success') {
                    let formData = [];
                    res.Data.forEach((item, index) => {
                        const [COLUMN_TYPE, COLUMN_LENGTH] = item.COLUMN_TYPE.split(/\(|\)/);
                        item.COLUMN_TYPE = COLUMN_TYPE;
                        item.COLUMN_LENGTH = COLUMN_LENGTH ? COLUMN_LENGTH : 0;
                        item.IS_NULLABLE = (item.IS_NULLABLE == 'NO' ? false : true)
                        item.PRIMARY = (item.CONSTRAINT_TYPE == 'PRIMARY KEY' ? true : false);
                        item.index = index;
                        item.Row_Status = '0';
                        let obj = configOriginal(item);
                        //系统字段默认备注
                        if (obj.COLUMN_NAME == 'Creater_SerialNumber' && obj.COLUMN_COMMENT == '') {
                            obj.COLUMN_COMMENT = '创建人';
                        } else if (obj.COLUMN_NAME == 'Create_Datetime' && obj.COLUMN_COMMENT == '') {
                            obj.COLUMN_COMMENT = '创建时间';
                        } else if (obj.COLUMN_NAME == 'Row_Status' && obj.COLUMN_COMMENT == '') {
                            obj.COLUMN_COMMENT = '行状态';
                        } else if (obj.COLUMN_NAME == 'Operation_ID' && obj.COLUMN_COMMENT == '') {
                            obj.COLUMN_COMMENT = '操作人';
                        } else if (obj.COLUMN_NAME == 'Operation_Datetime' && obj.COLUMN_COMMENT == '') {
                            obj.COLUMN_COMMENT = '操作时间';
                        }
                        formData.push(configOriginal(obj));
                    });
                    this.formData = formData;
                } else {
                    this.$message({
                        message: '系统错误，请联系开发者!',
                        type: 'error'
                    })
                }
            }).catch(xhr => {
                this.$message({
                    message: '系统错误，请联系开发者!',
                    type: 'error'
                })
            })
        },
        handleBack() {
            window.location.href = './index.html';
        },
        changeType(val, row) {
            if (val == 'varchar') {
                row.COLUMN_LENGTH = row.COLUMN_LENGTH_Original ? row.COLUMN_LENGTH_Original : '0';
                row.COLUMN_DEFAULT = row.COLUMN_DEFAULT_Original ? row.COLUMN_DEFAULT_Original : '';
            } else if (val == 'longtext') {
                row.COLUMN_LENGTH = '0';
                row.COLUMN_DEFAULT = 'NULL';
            }
        },
        InputLength(val, row) {
            row.COLUMN_LENGTH = val.replace(/\D/g, '');
        },
        handleAdd(formName) {
            if (formName == 'formData') {
                this[formName].push({
                    COLUMN_TYPE: 'varchar',
                    COLUMN_LENGTH: '100'
                });
            } else if (formName == 'indexData') {
                this[formName].push({});
            }
        },
        handleRemove(formName, obj) {
            if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                this[formName] = this[formName].filter(i => i.COLUMN_NAME != obj.COLUMN_NAME);
            } else {
                this[formName].filter(i => i.COLUMN_NAME == obj.COLUMN_NAME)[0].Row_Status = '1';
            }
        },
        handleSubmit() {
            const { SQL } = this.ALTER_TABLE;
            if (SQL) {
                this.loading = true;

                httpRequest({
                    hostApi: BASE_URL1,
                    url: '/generalDataTableOperation',
                    data: { Data: SQL }
                }).then(res => {
                    if (res.Status === 'success') {
                        this.$message.success("提交成功");
                        window.location.href = './index.html'
                    } else {
                        this.$message.error("提交失败，请稍后再试");
                    }
                }).catch(xhr => {
                    this.$message({
                        message: '系统错误，请联系开发者!',
                        type: 'error'
                    })
                })
            } else {
                this.$message.success("提交成功");
                window.location.href = './index.html';
            }
        }
    }
})